<template>
  <div class="app-container">


    <div class="filter-container">
      <el-button class="filter-item" icon="el-icon-circle-plus-outline" @click="showDialogVisible(null)">新增</el-button>
      <el-button class="filter-item" :icon="nodeOpenIcon" @click="foldList = []" :disabled="foldList.length === 0">
        全部展开
      </el-button>
      <el-button class="filter-item" :icon="nodeCloseIcon" @click="foldList = foldAllList"
                 :disabled="foldList === foldAllList">全部折叠
      </el-button>
    </div>
    <el-table
      :data="tableInfo.data"
      :row-style="toggleDisplayTr"
      border stripe
      class="init_table">
      <el-table-column
        align="center"
        width="55"
        type="index"
        label="序号">
      </el-table-column>

      <el-table-column
        label="权限名称"
        min-width="300"
        show-overflow-tooltip
        align="left">
        <template slot-scope="scope">
          <p @click="toggleFoldingStatus(scope.row)"
             :style="`margin-left: ${scope.row.__level * 16}px;margin-top:0;margin-bottom:0`"><i
            class="permission_toggleFold" :class="toggleFoldingClass(scope.row)"></i>{{scope.row.name}}</p>
        </template>
      </el-table-column>
      <!--<el-table-column-->
      <!--align="center"-->
      <!--width="90"-->
      <!--prop="__level"-->
      <!--label="层级">-->
      <!--</el-table-column>-->
      <!--<el-table-column-->
      <!--align="left"-->
      <!--prop="__identity"-->
      <!--label="节点标识">-->
      <!--</el-table-column>-->


      <el-table-column
        align="center"
        prop="id"
        min-width="80"
        show-overflow-tooltip
        label="编号">
      </el-table-column>


      <el-table-column
        align="center"
        prop="permission"
        min-width="80"
        label="权　值">
      </el-table-column>


      <el-table-column
        align="center"
        prop="url"
        min-width="80"
        label="路　径">
      </el-table-column>

      <el-table-column
        align="center"
        min-width="80"
        label="类　型">
        <template slot-scope="scope">
          <p v-if="scope.row.type==0"><i class="el-icon-link"/>菜单</p>
          <p v-else><i class="el-icon-mouse"/>按钮</p>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        min-width="80"
        label="状　态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.active==0" type="danger">停用</el-tag>
          <el-tag v-else type="success">启用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showDialogVisible(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog title="资源" :visible.sync="dialogVisible" width="60%" top="10vh">
      <el-form ref="submitForm" :rules="rules" :model="submitData" label-position="right" label-width="100px">

        <el-row>
          <el-col :span="11">
            <el-form-item label="父编号：" prop="pid">
              <el-input v-model="submitData.pid"/>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="名　称：" prop="name">
              <el-input v-model="submitData.name"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="11">
            <el-form-item label="权　值：" prop="permission">
              <el-input v-model="submitData.permission"/>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="路　径：" prop="url">
              <el-input v-model="submitData.url"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="11">
            <el-form-item label="序　号：" prop="orders">
              <el-input-number v-model="submitData.orders" @change="handleChange" :min="1"
                               label="描述文字"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="类　型：" prop="type">
              <el-radio-group v-model="submitData.type">
                <el-radio :label="0">菜单</el-radio>
                <el-radio :label="1">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="状　态：" prop="active">
              <el-radio-group v-model="submitData.active">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="operateType=='add'" type="primary" @click="handleAddData">确定</el-button>
        <el-button v-else type="primary" @click="handleModifyData">确定</el-button>
      </div>

    </el-dialog>


  </div>
</template>

<script>
  import {listAllResource, modifyResource, addResource} from '@/api/resource'
  import {handleRequest,toTree} from '@/utils/system'

  export default {
    data: () => ({
      dialogVisible: false,
      operateType: null,
      submitData: {
        id: null,
        pid: null,
        name: null,
        permission: null,
        path: null,
        type: null,
        orders: null,
        active: null
      },
      rules: {
        name: [{required: true, message: '不能为空', trigger: 'change'}],
        permission: [{required: true, message: '不能为空', trigger: 'change'}],
        url: [{required: true, message: '不能为空', trigger: 'change'}],
        type: [{required: true, message: '不能为空', trigger: 'change'}],
        active: [{required: true, message: '不能为空', trigger: 'change'}],
      },
      tableInfo:{
        data:[],
        minWidth: 50,
      },
      foldList: [], // 该数组中的值 都会在列表中进行隐藏  死亡名单
      nodeOpenIcon: 'el-icon-folder-opened',
      nodeCloseIcon: 'el-icon-folder',
      nodeLeafIcon: 'el-icon-document',

    }),
    computed: {
      /*********************************
       ** Fn: foldAllList
       ** Intro: 记录属性结构的首层节点
       ** Author: zyx
       *********************************/
      foldAllList() {
        return this.tableInfo.data.map(x => x.__identity)
      },
    },
    methods: {
      resetSubmitData() {
        this.submitData = {
          id: null,
          pid: null,
          name: null,
          permission: null,
          path: null,
          type: null,
          orders: null,
          active: null
        }
      },
      showDialogVisible(row) {
        this.resetSubmitData()
        this.operateType = 'add'
        this.dialogVisible = true

        if (row) {
          this.submitData = {...row}
          this.operateType = 'modify'
        }
        this.$nextTick(() => {
          this.$refs['submitForm'].clearValidate()
        })
      },
      handleAddData() {
        this.$refs['submitForm'].validate((valid) => {
          if (valid) {
            handleRequest({
              method: addResource,
              data: this.submitData,
              operateType: "新增",
              warnAlertShow: true,
              successAlertShow: true,
              failAlertShow: true,
              successCall: () => {
                this.createTree();
                this.dialogVisible = false;
              }
            })
          }
        })
      },

      handleModifyData() {
        this.$refs['submitForm'].validate((valid) => {
          if (valid) {
            handleRequest({
              method: modifyResource,
              data: this.submitData,
              operateType: "修改",
              warnAlertShow: true,
              successAlertShow: true,
              failAlertShow: true,
              successCall: () => {
                this.createTree();
                this.dialogVisible = false;
              }
            })
          }
        })
      },
      createTree() {
        handleRequest({
          method: listAllResource,
          successCall: (data) => {
            this.tableInfo.data = this.formatConversion([], toTree(data))
            console.log("this.tableInfo",this.tableInfo);
          }
        })
      },
      /*********************************
       ** Fn: toggleFoldingStatus
       ** Intro: 切换展开 还是折叠
       ** @params: params 当前点击行的数据
       ** Author: zyx
       *********************************/
      toggleFoldingStatus(params) {
        this.foldList.includes(params.__identity) ? this.foldList.splice(this.foldList.indexOf(params.__identity), 1) : this.foldList.push(params.__identity)
      },
      /*********************************
       ** Fn: toggleDisplayTr
       ** Intro: 该方法会对每一行数据都做判断 如果foldList 列表中的元素 也存在与当前行的 __family列表中  则该行不展示
       ** @params:
       ** Author: zyx
       *********************************/
      toggleDisplayTr({row, index}) {
        for (let i = 0; i < this.foldList.length; i++) {
          let item = this.foldList[i]
          // 如果foldList中元素存在于 row.__family中，则该行隐藏。  如果该行的自身标识等于隐藏元素，则代表该元素就是折叠点
          if (row.__family.includes(item) && row.__identity !== item) return 'display:none;'
        }
        return ''
      },
      /*********************************
       ** Fn: toggleFoldingClass
       ** Intro: 如果子集长度为0，则不返回字体图标。
       ** Intro: 如果子集长度为不为0，根据foldList是否存在当前节点的标识返回相应的折叠或展开图标
       ** Intro: 关于class说明：permission_placeholder返回一个占位符，具体查看class
       ** @params: params 当前行的数据对象
       ** Author: zyx
       *********************************/
      toggleFoldingClass(params) {
        return params.children.length === 0 ? this.nodeLeafIcon : (this.foldList.indexOf(params.__identity) === -1 ? this.nodeOpenIcon : this.nodeCloseIcon)
      },
      /*********************************
       ** Fn: formatConversion
       ** Intro: 将树形接口数据扁平化
       ** @params: parent 为当前累计的数组  也是最后返回的数组
       ** @params: children 为当前节点仍需继续扁平子节点的数据
       ** @params: index 默认等于0， 用于在递归中进行累计叠加 用于层级标识
       ** @params: family 装有当前包含元素自身的所有父级 身份标识
       ** @params: elderIdentity 父级的  唯一身份标识
       ** Author: zyx
       *********************************/
      formatConversion(parent, children, level = 0, family = [], elderIdentity = 'x') {
        // children如果长度等于0，则代表已经到了最低层
        // let page = (this.startPage - 1) * 10
        if (children.length > 0) {
          children.map((x, i) => {
            // 设置 __level 标志位 用于展示区分层级
            x['__level'] = level;
            // 设置 __family 为家族关系 为所有父级，包含本身在内
            x['__family'] = [...family, elderIdentity + '_' + i];
            // 本身的唯一标识  可以理解为个人的身份证咯 一定唯一。
            x['__identity'] = elderIdentity + '_' + i;
            parent.push(x)
            // 如果仍有子集，则进行递归
            if (x.children.length > 0) this.formatConversion(parent, x.children, level + 1, [...family, elderIdentity + '_' + i], elderIdentity + '_' + i)
          })
        }

        return parent
      }
    },
    created() {
      this.createTree();
    }
  }



</script>

<style>


  .app_title {
    display: block;
    width: 100%;
    font-size: 24px;
    line-height: 60px;
    color: #41dae4;
    text-align: center;
  }

  .permission_toggleFold {
    vertical-align: middle;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .permission_placeholder {
    display: inline-block;
    padding-right: 21px
  }
  
</style>
